package kr.couponplay.android.activity.intro.command;

import kr.couponplay.android.Constants;
import kr.couponplay.android.activity.R;
import kr.couponplay.android.activity.intro.IntroActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class ShortcutAddCommand implements Command {

	@Override
	public void execute(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
		String oldShoutcutYn1 = preferences.getString("addedShortcutYn", "N");
		String oldShoutcutYn2 = preferences.getString("addedShortcutYn_2", "N");

		if ("Y".equals(oldShoutcutYn1)) {
			removeShortcut(context, "쿠폰플레이");
		}
		if ("Y".equals(oldShoutcutYn2)) {
			removeShortcut(context, "소셜 쇼핑");
		}
		
    	String addedShortcutYn = preferences.getString(Constants.KEY_ADDED_SHORTCUT_YN, "N");
    	if ("Y".equals(addedShortcutYn)) {
    		return;
    	}
		
		addShortcut(context);
		Editor editor = preferences.edit();
		editor.putString(Constants.KEY_ADDED_SHORTCUT_YN, "Y");
		editor.commit();
	}

	private void addShortcut(Context context) {
		Intent shortcutIntent = new Intent(context.getApplicationContext(), IntroActivity.class);
		shortcutIntent.setAction(Intent.ACTION_MAIN);
		shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		
		Intent addIntent = new Intent();
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources().getString(R.string.app_name));
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(context, R.drawable.icon));
		addIntent.putExtra("duplicate", false);
		addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		context.getApplicationContext().sendBroadcast(addIntent);
	}

	private void removeShortcut(Context context, String name) {
		Intent shortcutIntent = new Intent();
		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent intent = new Intent();
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
		intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
		context.getApplicationContext().sendBroadcast(intent);
	}
}
